//这个文件专门用来存放关于收藏的所有接口
const Router = require('koa-router')
const collect = new Router()
const {exec} = require('../util/db')
// const db = require('../util/db')
const bodyparser = require('koa-bodyparser')
collect.use(bodyparser())//调用这个中间件 就可以拿到前端post过来的数据

collect.get('/uu', async (ctx) => {
    let searchSql = 'select * from user'
    let result=await exec(searchSql)
    ctx.body = result;
    console.log('---------------------')
})

//写对应的接口
// get请求
// http://localhost:3000/collect/list
collect.get('/list', async (ctx) => {
    let obj=ctx.query
    let selectSql = `select collect.userId,collect.drugId,drugName,drugImg from collect,drug_information where userId='${obj.userId}' and collect.drugId=drug_information.drugId`
    let res = await exec(selectSql)
    for(var i=0;i<res.length;i++){
        res[i].drugImg=`/drugImg${res[i].drugImg}`
    }
    ctx.body = res
})


// post请求
// http://localhost:3000/collect/collections
collect.post('/collections', async (ctx) => {
    console.log(ctx)
    var obj=ctx.request.body
    let selectSql = `select * from collect`
        let col = await exec(selectSql)
        let flag = false
        // 判断数据库user表中是否含有请求中的openid
        for (key in col) {
            if (col[key].userId == obj.userId && col[key].drugId == obj.drugId) {
                flag = true
            }
        }
        // 如果没有，则进行插入
        if (flag == false) {
            let insertSql = `insert into collect(userId,drugId) values('${obj.userId}','${obj.drugId}')`
            console.log(insertSql)

            await exec(insertSql)
            ctx.body = '收藏成功啦'
        } else {//如果有，则进行更新
            ctx.body = '已在收藏夹中'
        }
})


// delete请求
//http://localhost:3000/collect/collections
collect.delete('/collections', async (ctx) => {
    let obj = ctx.request.body
    console.log('-----------------')
    console.log(obj.itemId)
    for(var i in obj.itemId){
        console.log(i)
        let deleteSql = `delete from collect where userId='${obj.userId}' and drugId='${obj.itemId[i]}'`
        await exec(deleteSql)
    }
    
    ctx.body = '删除成功啦'
})


module.exports=collect